import axios from 'axios'
import $com from '@/utils/open/common'
import $constant from '@/utils/open/constant'
import eltool from '@/utils/open/eltool'
import store from '@/store'
import router from '@/router'


// 错误日志收集参数
let _params = {}
try {
  _params = {
    errType: 2,
    pageMsg: '',
    columnNo: '',
    lineNo: '',
    stack: '',
    cod: '',
    msg: '',
    controllerAddress: '',
    ipAddress: returnCitySN && returnCitySN['cip'],
    createTime: '',
    systemType: 3,
    dbName: 'pc_error_log'
  }
} catch (err) {
  console.log('err')
}
/**
 * 请求前置处理
 */
axios.defaults.timeout = 30000
axios.defaults.withCredentials = true
axios.defaults.baseURL = "/"
axios.interceptors.request.use(config => {
  // console.log('request-config', config)
  // const authSession = $com.getCookie('AUTH-SESSION')
  // const gatewaySession = $com.getCookie('GATEWAY-SESSION')
  // config.headers['accept'] = 'application/json; charset=utf-8'
  // config.headers['Cookie'] = authSession + ' ;' + gatewaySession
  // const uuid = $com.uuid()
  // console.log('uuid', uuid)
  // config.headers['GUID_AVOID_REPEATED_TOKEN'] = uuid
  //
  // debugger
  // AUTH-SESSION=N2Q1M2Q1ZDEtZGJhMC00NjBjLWJlYjAtYWM5MTU2MTdkMzMw; GATEWAY-SESSION=440343e4-281d-41c1-8760-6ef0afd456fc
  //
  // debugger
  // const urlParam = $com.getKeyVal('user', 'firstUrlParam', 'sessionStorage') || {}
  // config.headers['Authorization'] = urlParam.access_token || ''
  // debugger
  // console.log('config', config)

  return config
}, function (err) {
  return Promise.reject(err)
})
/**
 * 请求后置处理
 *
 */
axios.interceptors.response.use(res => {
  // debugger
  // console.log('response-res', res)
  // debugger

  if (res.config.headers && res.config.headers['responseType'] === 'blob') {
    download(res)
    return
  }
  if (res.status === 200) {
    if (!getCodeMsg(res.data)) {
      return Promise.reject()
    }
  } else if (res.status === 401) {
    // debugger
    $com.goLoginFn()
  }
  return res.data
}, (err) => {
  // console.log('response', err)

  // debugger
  const errMsg = err.toString()
  const code = errMsg.substr(errMsg.indexOf('code') + 5)
  // debugger
  if (!getStatusMsg(parseInt(code), err)) {
    _params.msg = errMsg
    _params.stack = '错误原因:' + errMsg + ',定位页面路由：' + window.location.hash.slice(1)
    _params.createTime = Date.now()
  }
  return Promise.reject()
})

/**
 * 下载主方法
 * @param res
 */
function download(res) {
  const blob = new Blob([res.data])
  const filename = res.config.params['fileName']
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}
export default {
  /**
   * 小文件下载方法
   * @param url
   * @param params
   * @param fileName  下载文件的名称，包括后缀
   * @returns {*|Promise<any>}
   */
  download(url, params, fileName) {
    const headers = {
      'content-type': 'application/x-www-form-urlencoded',
      'responseType': 'blob'
    }
    params.fileName = fileName
    return new Promise((resolve, reject) => {
      const URL = url.indexOf('http') !== -1 ? url : $constant.ctx + url
      axios({
        method: 'get',
        baseURL: URL,
        params: params,
        headers: headers,
        responseType: 'blob'
      }).then((res) => {
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },

  /**
   * GET 资源请求
   * 特别用于查询操作
   * @param url
   * @param params
   * @returns {*}
   */
  get(url, params) {
    const headers = {
      'content-type': 'application/x-www-form-urlencoded'
    }
    // debugger
    return this.createForm(url, 'get', headers, params)
  },
  /**
   * DELETE 资源请求
   * 特用于删除操作
   * @param url
   * @param params
   * @returns {*}
   */
  delete(url, params) {
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    return this.createForm(url, 'delete', headers, params)
  },
  /**
   * POST 资源请求
   * 特用于保存操作，支持DTO
   * @param url
   * @param params
   * @returns {*}
   */
  postJson(url, params) {
    // console.log(params)
    const headers = {
      'Content-Type': 'application/json; charset=utf-8'
    }
    // debugger
    params = JSON.stringify(params)
    return this.createJson(url, 'post', headers, params)
  },
  /**
   * POST 资源请求
   * 特用于保存操作，支持FORM参数提交
   * @param url
   * @param params
   * @returns {*}
   */
  postForm(url, params) {
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    // debugger
    return this.createForm(url, 'post', headers, params)
  },
  /**
   * PUT 资源请求
   * 特用于保存操作，支持DTO
   * @param url
   * @param params
   * @returns {*}
   * 使用示例：
   * this.$request.putJson(this.ctx + this.dispense + '/api/v1/ysleaveauth/update', params).then(res => {
        if (res) {
          that.carryOff(that, params)
        }
      }).catch(res => {
        that.form.btnLoading = false
      })
   */
  putJson(url, params) {
    const headers = {
      'Content-Type': 'application/json; charset=utf-8'
    }
    params = JSON.stringify(params)
    return this.createJson(url, 'put', headers, params)
  },
  /**
   * PUT 资源请求
   * 特用于保存操作，支持FORM参数提交
   * @param url
   * @param params
   * @returns {*}
   */
  putForm(url, params) {
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    return this.createForm(url, 'put', headers, params)
  },
  /**
   * 原生请求 支持FORM表单参数提交
   * @param url
   * @param method
   * @param headers
   * @param params
   * @returns {Promise<any>}
   */
  createForm(url, method, headers, params) {
    headers = headers || {}
    // debugger
    const URL = url.indexOf('http') !== -1 ? url : $constant.ctx + url
    // debugger
    return new Promise((resolve, reject) => {
      axios({
        method: method,
        baseURL: URL,
        params: params,
        headers: headers
      }).then((res) => {
        // debugger
        resolve(res)
      }).catch((err) => {
        _params.controllerAddress = url
        // this.postJson(common.static.ctx + 'basics/api/v1/log/insert/pc_error_log', _params)
        // debugger
        console.error('err', _params);
        reject(err)
      })
    })
  },
  /**
   * 原生请求 支持DTO 提交
   * @param url
   * @param method
   * @param headers
   * @param params
   * @returns {Promise<any>}
   */
  createJson(url, method, headers, params) {
    return new Promise((resolve, reject) => {
      // debugger
      axios({
        method: method,
        baseURL: $constant.ctx + url,
        data: params,
        headers: headers
      }).then((res) => {
        // debugger
        resolve(res)
      }).catch((err) => {
        // debugger
        _params.controllerAddress = url
        console.error('err', _params);
        // this.postJson(common.static.ctx + 'basics/api/v1/log/insert/pc_error_log', _params)
        reject(err)
      })
    })
  }
}

/**
 * 获取业务code 转移提醒
 * @param code=== 200
 * @returns {boolean}
 */
function getCodeMsg(res) {
  // debugger
  if (res.code === 200) {
    return true
  } else if (res.code === -1) {
    eltool.errorMsg('服务器出现异常！')
    return false
  } else {
    eltool.errorMsg(res.message)
    return false
  }

  // switch (res.code === 200) {
  //   case -1:
  //     eltool.errorMsg('服务器出现异常！')
  //     return false
  //   case 601:
  //     eltool.errorMsg('验证码错误！')
  //     return false
  //   case 602:
  //     eltool.errorMsg('账号被禁用，请联系管理员！')
  //     return false
  //   case 600:
  //     eltool.errorMsg('账号验证错误！')
  //     return false
  //   default:
  //     return true
  // }
}
/**
 * 获取响应状态 转义提醒
 * @param code
 * @returns {boolean}
 */
function getStatusMsg(code, msg) {
  // debugger
  switch (code) {
    case 401:
      eltool.errorMsg(msg || '登录凭证已失效！')
      $com.goLoginFn() // 重新登录
      return false
    case 403:
      eltool.errorMsg(msg || '您没有操作权限！')
      return false
    case 500:
      eltool.errorMsg(msg || '服务器出异常！')
      return false
    case 505:
      eltool.errorMsg(msg || '服务器出异常！')
      return false
    case 404:
      eltool.errorMsg(msg || '请求地址找不到！')
      return false
    default:
      eltool.errorMsg(msg || '请求异常！')
      return true
  }
}
